package com.ldr.custom.spring.factory;

import com.ldr.custom.spring.enums.ConvertStrategyEnum;
import com.ldr.custom.spring.strategy.ConvertStrategy;

/**
 * 设计模式：简单工厂模式、懒汉式单例，策略模式
 * 数据类型转换工厂
 */
public class ConvertFactory {


    private ConvertFactory() {

        synchronized (ConvertFactory.class) {
            if (LazyConvertFactory.convertFactory != null) {
                throw new RuntimeException("单例已经被侵犯");
            }
        }
    }

    public static ConvertFactory getInstance() {
        return LazyConvertFactory.convertFactory;
    }



    public ConvertStrategy getConvertStrategy(Class<?> type) throws IllegalAccessException, InstantiationException {
        //策略模式，寻找对应转换策略
        Class<?> clazz = ConvertStrategyEnum.findObjByType(type);
        if (clazz == null) {
            throw new RuntimeException("没有找到对应转换策略");
        }
        ConvertStrategy convertStrategy = (ConvertStrategy) clazz.newInstance();
        if (!convertStrategy.isSupport(convertStrategy)) {
            throw new RuntimeException("转换策略不匹配");
        }

        return convertStrategy;
    }


    private static class LazyConvertFactory {
        private final static ConvertFactory convertFactory = new ConvertFactory();
    }


}
